package com.supermap.dataservice.cloud.china;


import com.alibaba.dubbo.config.annotation.Service;
import com.supermap.dataservice.cloud.productC.ProductCloudMapper;
import com.supermap.dataservice.mysql.config.DynamicDataSourceContextHolder;
import com.supermap.dataservice.util.DateUtil;
import com.supermap.dataservice.util.JSONUtil;
import com.supermap.dataservice.util.JSONUtils;
import com.supermap.dubbo.api.alltype.entity.AllType;
import com.supermap.dubbo.api.cloud.china.AgrStaObj;
import com.supermap.dubbo.api.cloud.china.StatisticsService;
import io.swagger.models.auth.In;
import org.apache.neethi.All;


import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author aqua
 * @description
 * @date 2018年12月12 下午 3:30
 * @email 1301584033@qq.com
 */
@Service
public class StatisticsServiceImpl implements StatisticsService {
    @Resource
    private  StatisticsMpper statisticsMpper;
    @Resource
    private ProductCloudMapper productCloudMapper;
    @Resource
    private SyntheticalStatisticsMapper syntheticalStatisticsMapper;

    @Override
    public JSONUtil getAdvUploadByCropId(String cropId) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        //初始化Json封装工具类
        Map m=new HashMap();
        List<Map<String,Object>> childNode= statisticsMpper.getCropChildNode(cropId);
        for(int i=0;i<childNode.size();i++){
            int[] adv=new int[12];
            List<Map<String,Object>> yearUploadCountSum=statisticsMpper.getYearUpdataLoadCountSum((String)childNode.get(i).get("code"));
            for(int j=0;j<yearUploadCountSum.size();j++){
                Integer mon = (Integer) yearUploadCountSum.get(j).get("mon");
                Long nums = (Long) yearUploadCountSum.get(j).get("nums");
                adv[mon-1]=nums.intValue();
            }
            m.put(childNode.get(i).get("name"),adv);
        }

        return new JSONUtil().setData(m);
    }

    @Override
    public JSONUtil getAllTypeList(String areaCode,String cropId) {
        Map<String, Object> m=new HashMap();
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        String  cropName=  productCloudMapper. getCropNameBuCropId(cropId);
        if(cropId!=null){
            cropId=productCloudMapper.getCropGroupConcat(cropId);
            cropId=cropId.replace(",","\",\"");
            cropId="\""+cropId+"\"";
        }
        List<AllType> advList = statisticsMpper.getAllTypeToAdvList(areaCode,cropId);
        m.put("咨询", advList);
        List<AllType> agrList = statisticsMpper.getAllTypeToAgrList(areaCode,cropId);
        m.put("农情", agrList);
        List<AllType> disList = statisticsMpper.getAllTypeToDisList(areaCode,cropId);
        disList.addAll(statisticsMpper.getAllTypeToDisDIPListSql(areaCode,cropId));
        m.put("灾情", disList);
        if(cropId!=null){
            DynamicDataSourceContextHolder.setDataSourceKey("ds1");
            List<Map<String, Object>> product=new ArrayList<>();

            List<AllType> cpList1 = statisticsMpper.getAllTypeToProductList2(cropName);
            DynamicDataSourceContextHolder.setDataSourceKey("ds2");
            for (int i=0;i<cpList1.size();i++){
                Map<String, Object> chinodeProduct=new HashMap();
                chinodeProduct.put("上传",cpList1.get(i));
                if(cpList1.get(i).getAreaCode().length()<4){
                    List<String> list=statisticsMpper.getAllareaCode(cpList1.get(i).getAreaCode());
                    List<Map<String,Object>> list1=new ArrayList<>();
                    for (String str:list){
                        list1.addAll(statisticsMpper.getUserLonLateByAreaCode(str));
                    }
                    chinodeProduct.put("下发",list1);
                }else{
                    chinodeProduct.put("下发",statisticsMpper.getUserLonLateByAreaCode(cpList1.get(i).getAreaCode()));
                }

                product.add(chinodeProduct);
            }
            m.put("公共服务产品", product);
            List<Map<String, Object>> expertProduct=new ArrayList<>();

           // List<AllType> cpList2 = statisticsMpper.getAllTypeToExpertList(cropId);
            //专家建议
            List<AllType> cpList3 = statisticsMpper.getAllTypeToSuggestList(cropId);
            //cpList2.addAll(cpList3);
            for (int i=0;i<cpList3.size();i++){
                Map<String, Object> expertProductNode=new HashMap();
                expertProductNode.put("上传",cpList3.get(i));
                expertProductNode.put("下发",statisticsMpper.getFarmLonLateByAreaCode(cpList3.get(i).getId()));
                expertProduct.add(expertProductNode);
            }
            m.put("专家产品",expertProduct);
        }else{
            DynamicDataSourceContextHolder.setDataSourceKey("ds3");
            List<AllType> cpList = statisticsMpper.getAllTypeToProductList(areaCode);
            m.put("产品", cpList);
            DynamicDataSourceContextHolder.setDataSourceKey("ds2");
            List<AllType> areaList = statisticsMpper.getAreaByCode(areaCode);
            m.put("geo", areaList);
        }
        return new JSONUtil().setData(m);
    }

    @Override
    public JSONUtil getProductCountSum(String areaCode) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds1");
        Map<String, Integer> map=new HashMap<>();
        map.put("公共服务产品",statisticsMpper.getProductCountSum(areaCode));
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        Integer count= statisticsMpper.getExpertProductCountSum(areaCode);
        map.put("模型产品",218);
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        map.put("专家产品",count+statisticsMpper.getExpertProductCountSum1(areaCode));
        return  new JSONUtil().setData(map);
    }

    @Override
    public JSONUtil getFarmLandDistribution(String areaCode) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        return new JSONUtil().setData(statisticsMpper.getFarmALLCounSum(areaCode));
    }

    @Override
    public JSONUtil getSerObjListByAreacode(String areaCode,String month,String cropId) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        if(cropId!=null){
            cropId= productCloudMapper.getCropGroupConcat(cropId);
            cropId=cropId.replace(",","\",\"");
            cropId="\""+cropId+"\"";

        }

        return new JSONUtil().setData(statisticsMpper.getSerObjListByAreacode(areaCode,month,cropId));
    }

    @Override
    public JSONUtil getAgrByareaCode(String areaCode) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateTime=format.format(new Date());
        Integer mont=Integer.valueOf(dateTime.substring(5,7).replaceAll("0",""));
        Calendar cale = Calendar.getInstance();
        cale = Calendar.getInstance();
        cale.add(Calendar.MONTH, 1);
        cale.set(Calendar.DAY_OF_MONTH, 0);
        Calendar cal = Calendar.getInstance();
        String endTime=format.format(cale.getTime())+" 23:59:59";
        cale = Calendar.getInstance();
        cale = Calendar.getInstance();
        cale.add(Calendar.YEAR,-1);
        cale.add(Calendar.MONTH, 1);
        cale.set(Calendar.DAY_OF_MONTH, 0);
        String beginTime=format.format(cale.getTime())+" 23:59:59";
        List<AgrStaObj> mapList= statisticsMpper.getSubject();
        for(AgrStaObj agrStaObj:mapList) {
            //获取农田
            List<Map<String, Object>> agrList = statisticsMpper.getAgrInfo(areaCode, beginTime, endTime, Integer.valueOf(agrStaObj.getCode()));
            int[] allagr = new int[12];
            for (int i = 1; i < 13; i++) {
                if (i + mont > 12) {
                    allagr[i - 1] = i + mont - 12;
                } else {
                    allagr[i - 1] = i + mont;
                }

            }

            if (agrList.size() > 0) {
                Map<Integer, String> mapCount = new HashMap<>();
                for (Map<String, Object> map : agrList) {
                    Integer mon = (Integer) map.get("mon");
                    Long nums = (Long) map.get("nums");
                    for (int i = 0; i < 12; i++) {
                        if (allagr[i] == mon) {
                            allagr[i] =  nums.intValue();
                            mapCount.put(i, "");
                        }
                    }

                }
                for (int i = 0; i < 12; i++) {
                    if (mapCount.get(i) == null) {
                        allagr[i] = 0;
                    }
                }
            } else {
                allagr = new int[12];

            }
            agrStaObj.setData(allagr);

        }
        return new JSONUtil().setData(mapList);
    }

    @Override
    public List<AllType> getCQProduct() {
        DynamicDataSourceContextHolder.setDataSourceKey("ds1");
        return statisticsMpper.getCQProduct();
    }

    @Override
     public List<AllType> getExpretProductList()
    {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        return statisticsMpper.getExpretProductByAreaCode();
    }

    @Override
    public JSONUtils syntheticalStatistics(String areaCode, String startDate, String endDate) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        if (startDate == null || "".equals(startDate)){
            startDate = "1900-01-01 00:00:00";
        }else {
            startDate = startDate +  " 00:00:00";
        }
        if (endDate == null || "".equals(endDate)) {
            endDate = DateUtil.DateToString(new Date(), "yyyy-MM-dd") + " 23:59:59";
        }else{
            endDate = endDate + " 23:59:59";
        }
        List<Map<String , Object>> resultList = syntheticalStatisticsMapper.SyntheticalStatistics(areaCode,startDate,endDate);
        List<Map<String , Object>> expertProductList = syntheticalStatisticsMapper.syntheticalStatisticsByExpertProduct(areaCode , startDate , endDate);
        List<Map<String , Object>> activeExpertList = syntheticalStatisticsMapper.syntheticalStatisticsByActiveExpert(areaCode , startDate ,endDate);

        for ( Map<String , Object> map: resultList) {
                String areaName = map.get("areaname").toString();
            for (Map<String , Object> emap: expertProductList) {
                String areaName1 = emap.get("areaname").toString();
                if (areaName != null && areaName1 != null && areaName.equals(areaName1))
                {
                    for (String key: emap.keySet()) {
                        map.put(key , emap.get(key));
                    }
                }
            }
            for (Map<String , Object> amap: activeExpertList) {
                String areaName2 = amap.get("areaname").toString();
                if (areaName != null && areaName2 != null && areaName.equals(areaName2))
                {
                    for (String key: amap.keySet()) {
                        map.put(key , amap.get(key));
                    }
                }
            }
        }


        return new JSONUtils().setData(resultList).setCountSum(resultList != null ? resultList.size():0);
    }

    @Override
    public JSONUtils publicProductStatistics(String areaCode, String startDate, String endDate) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds1");
        if (startDate == null || "".equals(startDate)) {
            startDate = "1900-01-01";
        }else{
            startDate = startDate + " 00:00:00";
        }
        if (endDate == null || "".equals(endDate)){
            endDate = DateUtil.DateToString(new Date(),"yyyy-MM-dd");
        }else{
            endDate = endDate + " 23:59:59";
        }
        List<Map<String , Object>> resultList = syntheticalStatisticsMapper.publicProductStatistics(areaCode,startDate,endDate);;
        return new JSONUtils().setData(resultList).setCountSum(resultList != null ? resultList.size():0);
    }


}
